var mongoose = require('mongoose');
var News = require('../models/news.model');
var Comment = require('../models/comment.model');
var async = require('async')

exports.create = function(req,res,next){
    const news = new News(req.body); // req.body
    news.save(function (err,data) {
        if (err) {
          console.log(err);
        } else {
          res.json(data);
        }
      });

}

exports.update = function(req,res,next){
    const id =mongoose.Types.ObjectId(req.params.id);
    // 从User这个数据模型里去找ID的对象并且将它进行更新操作
    News.findByIdAndUpdate(id, {$set: req.body},{new:false})
    .then(data=>{
        // 这个data数据返回的是没有修改之前的数据
        res.json(data);
    })
}

exports.remove = function(req,res,next){
    const id = req.params.id;
    // 从User这个数据模型里去找ID的对象并且将它进行更新操作
    News.findByIdAndRemove(id, function(err,data){
        res.json({"message":"delete ok"});
    })
}

exports.removes=function(req,res,next){
    var ids=req.body.ids;
    
    News.remove({_id:{$in:ids}}).then(data=>{
        res.json({'removes':'ok'})
    })
    
}

exports.list = function(req,res,next){
   var page = (req.body.page) ? req.body.page: 1;
   var limit = (req.body.limit) ? req.body.limit: 5;
   // 查询条件
   var queryCondition = {};
   if(req.body.cateId && req.body.cateId.trim().length>0){
    cateId = req.body.cateId;
    queryCondition = {
        cateId:cateId,
        }
    }
    if(req.body.id && req.body.id.trim().length>0){
        id = req.body.id;
        queryCondition = {
            _id:mongoose.Types.ObjectId(id),
            }
        }
   if(req.body.title && req.body.title.trim().length>0){
    title = req.body.title;
       queryCondition = {
            "title": new RegExp(title,"i")
       }
   }
   console.log(queryCondition)
   News.paginate(queryCondition,{page: page,limit:limit},function(err,results){
    // //    res.json(results)//
    //    for(let i=0;i<results.docs.length;i++){
    //        Comment.count({newId: results.docs[i]._id}).then(data=>{
    //            console.log(data)
    //            results.docs[i].commentCount = data;
               
    //        })
    //    }
    //    res.json(results)
    //利用map对用户结果进行循环便利
    console.log(results,111)
        async.map(results.docs,function(news,done){
            Comment.count({newId:news._id}).then(data=>{
                //console.log(data)
                news.commentCount = data;
                done(null,news)
            })
        },function(err){
            res.json(results)
        })
   })

}